"""
租户配置模型
"""
from app.core.extensions import db
import datetime
import json


class TenantConfig(db.Model):
    """租户配置表"""
    __tablename__ = 'tenant_configs'

    id = db.Column(db.Integer, primary_key=True)
    tenant_id = db.Column(db.Integer, db.ForeignKey('tenants.id'), nullable=False, comment='租户ID')
    config_type = db.Column(db.String(50), nullable=False,
                            comment='配置类型：wechat_mp, wechat_pay, wechat_gzh, doubao_ai等')
    config_key = db.Column(db.String(100), nullable=False, comment='配置键名')
    config_value = db.Column(db.Text, comment='配置值')
    is_encrypted = db.Column(db.Boolean, default=False, comment='是否加密存储')
    description = db.Column(db.String(255), comment='配置描述')
    created_at = db.Column(db.DateTime, default=datetime.datetime.now)
    updated_at = db.Column(db.DateTime, onupdate=datetime.datetime.now)

    # 联合唯一索引
    __table_args__ = (
        db.UniqueConstraint('tenant_id', 'config_type', 'config_key', name='uk_tenant_config'),
        db.Index('idx_tenant_config_type', 'tenant_id', 'config_type'),
    )

    def to_dict(self):
        return {
            'id': self.id,
            'tenant_id': self.tenant_id,
            'config_type': self.config_type,
            'config_key': self.config_key,
            'config_value': self.config_value,
            'is_encrypted': self.is_encrypted,
            'description': self.description,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }


class TenantConfigService:
    """租户配置服务"""

    @staticmethod
    def get_config(tenant_id, config_type, config_key, default_value=None):
        """获取租户配置"""
        config = TenantConfig.query.filter_by(
            tenant_id=tenant_id,
            config_type=config_type,
            config_key=config_key
        ).first()

        if config:
            value = config.config_value
            # 如果是JSON格式，尝试解析
            if value and (value.startswith('{') or value.startswith('[')):
                try:
                    return json.loads(value)
                except:
                    pass
            return value

        return default_value

    @staticmethod
    def set_config(tenant_id, config_type, config_key, config_value, description=None, is_encrypted=False):
        """设置租户配置"""
        # 如果是字典或列表，转为JSON
        if isinstance(config_value, (dict, list)):
            config_value = json.dumps(config_value, ensure_ascii=False)

        config = TenantConfig.query.filter_by(
            tenant_id=tenant_id,
            config_type=config_type,
            config_key=config_key
        ).first()

        if config:
            config.config_value = config_value
            config.description = description
            config.is_encrypted = is_encrypted
            config.updated_at = datetime.datetime.now()
        else:
            config = TenantConfig(
                tenant_id=tenant_id,
                config_type=config_type,
                config_key=config_key,
                config_value=config_value,
                description=description,
                is_encrypted=is_encrypted
            )
            db.session.add(config)

        db.session.commit()
        return config

    @staticmethod
    def get_all_configs(tenant_id, config_type=None):
        """获取租户的所有配置"""
        query = TenantConfig.query.filter_by(tenant_id=tenant_id)
        if config_type:
            query = query.filter_by(config_type=config_type)

        configs = query.all()
        result = {}

        for config in configs:
            if config.config_type not in result:
                result[config.config_type] = {}

            value = config.config_value
            # 尝试解析JSON
            if value and (value.startswith('{') or value.startswith('[')):
                try:
                    value = json.loads(value)
                except:
                    pass

            result[config.config_type][config.config_key] = value

        return result

    @staticmethod
    def delete_config(tenant_id, config_type, config_key):
        """删除租户配置"""
        config = TenantConfig.query.filter_by(
            tenant_id=tenant_id,
            config_type=config_type,
            config_key=config_key
        ).first()

        if config:
            db.session.delete(config)
            db.session.commit()
            return True
        return False


# 配置类型常量
class ConfigTypes:
    WECHAT_MP = 'wechat_mp'  # 微信小程序
    WECHAT_PAY = 'wechat_pay'  # 微信支付
    WECHAT_GZH = 'wechat_gzh'  # 微信公众号
    DOUBAO_AI = 'doubao_ai'  # 豆包AI
    SYSTEM = 'system'  # 系统配置
    CUSTOM = 'custom'  # 自定义配置
    TCOS = 'tcos'  # 腾讯云对象存储

# 预定义配置项
PREDEFINED_CONFIGS = {
    ConfigTypes.WECHAT_MP: {
        'app_id': '微信小程序AppID',
        'app_secret': '微信小程序AppSecret',
    },
    ConfigTypes.WECHAT_PAY: {
        'mch_id': '商户号',
        'api_key': 'API密钥',
        'cert_path': '证书路径',
        'key_path': '私钥路径'
    },
    ConfigTypes.WECHAT_GZH: {
        'app_id': '公众号AppID',
        'app_secret': '公众号AppSecret',
        'token': 'Token',
        'encoding_aes_key': 'EncodingAESKey'
    },
    ConfigTypes.DOUBAO_AI: {
        'api_key': 'API密钥',
        'base_url': 'API地址',
        'model': '模型名称'
    },
    ConfigTypes.TCOS: {
        'secret_id': '腾讯云SecretId',
        'secret_key': '腾讯云SecretKey',
        'region': '地域标识符(如ap-beijing)',
        'bucket': '存储桶名称'
    },
}


